package top.eggcode.arm.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import top.eggcode.arm.model.App;
import top.eggcode.arm.model.AppForm;
import top.eggcode.arm.model.AppQuery;
import top.eggcode.arm.model.AppView;
import top.eggcode.arm.service.AppService;
import top.eggcode.arm.store.AppStore;
import top.eggcode.common.base.PackBaseController;
import top.eggcode.common.lang.BeanUnit;
import top.eggcode.common.model.ListPage;
import top.eggcode.common.model.ResponseResult;
import top.eggcode.common.mvc.Responser;
import top.eggcode.plugins.dict.Translate;

import javax.annotation.Resource;

@Api(tags = "应用管理")
@RequestMapping("/api/arm/apps")
@RestController
public class AppController extends PackBaseController {

    @Resource
    private AppStore appStore;

    @Resource
    private AppService appService;

    /**
     * 配置
     * 监控方式、网络延迟等
     *
     * @return
     */
    @GetMapping("/config")
    public ResponseResult<?> config() {

        return Responser.successful();
    }

    /**
     * 配置
     * 监控方式、网络延迟等
     *
     * @return
     */
    @PostMapping("/add")
    public ResponseResult<?> add(@RequestBody AppForm form) {

        App app = BeanUnit.transfer(form, App.class);
        if (form.getMode() == 2) {
            app.setParams(JSON.toJSONString(form.getHttpConf()));
        } else if (form.getMode() == 3) {
            app.setParams(JSON.toJSONString(form.getSocketConf()));
        }
        app.markCreated();
        appService.put(app);
        return Responser.successful();
    }

    @GetMapping("/all")
    public ResponseResult<?> add() {

        return Responser.successful();
    }

    @PostMapping("/detail")
    public ResponseResult<?> detail(@PathVariable String id) {

        return Responser.successful(appStore.getOne(id));
    }


    @Translate
    @PostMapping("/query_list")
    public ResponseResult<?> queryPage(@RequestBody AppQuery query) {
        ListPage<AppView> page = appStore.queryPage(query);

        return Responser.successful(page);
    }

    @PostMapping("/modify")
    public ResponseResult<?> modify(@RequestBody AppForm form) {

        App app = BeanUnit.transfer(form, App.class);
        if (form.getMode() == 2) {
            app.setParams(JSON.toJSONString(form.getHttpConf()));
        } else if (form.getMode() == 3) {
            app.setParams(JSON.toJSONString(form.getSocketConf()));
        }
        app.markUpdated();
        appService.put(app);
        return Responser.successful();
    }

    @PostMapping("/delete")
    public ResponseResult<?> delete(@RequestParam String id) {
        App app = appStore.getOne(id);
        app.markDeleted();
        appStore.save(app);
        return Responser.successful();
    }
}
